﻿
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using XiAnAirport.BUS;
using XiAnAirport.DAL;
using XiAnAirport.Models;

namespace XiAnAirport.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class UpLoadController : ControllerBase
    {

        [Obsolete]
        private readonly IHostingEnvironment _hostingEnvironment;
        private JwtSettings _jwtSettings;
        JwtToken _jwttoken = new JwtToken();
        IHttpContextAccessor _access;

        [Obsolete]
        public UpLoadController(IHostingEnvironment hostingEnvironment, IOptions<JwtSettings> jwtSettingsAccesser, IHttpContextAccessor access)
        {
            _hostingEnvironment = hostingEnvironment;
            _jwtSettings = jwtSettingsAccesser.Value;

            _access = access;
        }

        /// <summary>
        /// 上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("UpLoadFile")]
        [Obsolete]
        public ResponseMessage UpLoadFile([FromForm] IFormCollection formCollection)
        {
            ResponseMessage message = new ResponseMessage();
            string webRootPath = _hostingEnvironment.ContentRootPath;
            List<UploadFileEntity> uploadFileList = new List<UploadFileEntity>();
            FormFileCollection filelist = (FormFileCollection)formCollection.Files;
            try
            {
                foreach (IFormFile file in filelist)
                {
                    string name = file.FileName;
                    string type = System.IO.Path.GetExtension(name);
                    if (!(type.ToLower().Contains("jpg") || type.ToLower().Contains("jpeg") || type.ToLower().Contains("png")))
                    {
                        message.errcode = 1;
                        message.errmsg = "上传格式错误";
                        message.data = null;
                        message.total = 0;
                        return message;
                    }
                    UploadFileEntity content = new UploadFileEntity();

                    String Tpath = "/img/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";

                    string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    string FilePath = webRootPath + "/wwwroot" + Tpath;


                    DirectoryInfo di = new DirectoryInfo(FilePath);


                    if (!di.Exists) { di.Create(); }

                    using (FileStream fs = System.IO.File.Create(FilePath + FileName + type))
                    {
                        // 复制文件
                        file.CopyTo(fs);
                        // 清空缓冲区数据
                        fs.Flush();
                        fs.Close();
                        //string hostip = GetLocalIp();
                        //int port = Request.HttpContext.Connection.LocalPort;
                        //string hostip = Request.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString();
                        content.FileName = FileName + type;
                        content.FilePath = Tpath;
                    }

                    uploadFileList.Add(content);
                }
                message.errcode = 0;
                message.errmsg = "";
                message.data = uploadFileList;
                message.total = 1;
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = "上传异常";
                message.data = null;
                message.total = 0;
                LogHelper.Log(e.ToString());
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "上传文件";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
            }

            return message;
        }

        /// <summary>
        /// 导入保养计划
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("ImportMaintain")]
        [Obsolete]
        public ResponseMessage ImportMaintain([FromForm] IFormCollection formCollection)
        {
            ResponseMessage message = new ResponseMessage();
            string filepath = string.Empty;
            string result = string.Empty;
            MaintainBUS bus = new MaintainBUS();
            try
            {
                string webRootPath = _hostingEnvironment.ContentRootPath;

                FormFileCollection filelist = (FormFileCollection)formCollection.Files;
                foreach (IFormFile file in filelist)
                {
                    string name = file.FileName;
                    string type = System.IO.Path.GetExtension(name);
                    if (!(type.ToLower().Contains("xls") || type.ToLower().Contains("xlsx")))
                    {
                        message.errcode = 1;
                        message.errmsg = "上传格式错误";
                        message.data = null;
                        message.total = 0;
                        return message;
                    }
                    DataTable data = new DataTable();
                    filepath = bus.UploadFileToServer(file, webRootPath);
                    data = ExcelTools.ImportCompareMeanExcel(filepath);

                    result += bus.ImportTableToData(data);
                    MaintainDAL maintainDAL = new MaintainDAL();
                    maintainDAL.DeleteDistinctMaintain();
                }
                if (result.Contains("失败"))
                {
                    message.errcode = 1;
                    message.errmsg = result;
                    message.data = null;
                    message.total = 0;
                    LogHelper.Log(result);
                }
                else
                {
                    message.errcode = 0;
                    message.errmsg = "";
                    message.data = null;
                    message.total = 0;
                    if (message.errcode == 0)
                    {
                        string username = HttpContext.Session.GetString("UserName").ToString();
                        LogBUS logBUS = new LogBUS();
                        OperationLog operationLog = new OperationLog();
                        operationLog.operation = "导入保养计划";
                        operationLog.operatorName = username;
                        logBUS.InsertOperationLog(operationLog);
                    }
                }
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = "导入保养计划异常";
                message.data = "";
                message.total = 0;
                LogHelper.Log(e.ToString());
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "导入保养计划";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
            }
            return message;
        }
    }
}
